package com.luo.backend.repository;

import com.luo.backend.entity.GroupBuyingActivity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 团购活动仓储接口
 */
@Repository
public interface GroupBuyingActivityRepository extends JpaRepository<GroupBuyingActivity, Long> {
    
    /**
     * 查找活跃的团购活动
     */
    @Query("SELECT g FROM GroupBuyingActivity g WHERE g.status = 'active' AND g.endTime > CURRENT_TIMESTAMP ORDER BY g.createdAt DESC")
    Page<GroupBuyingActivity> findActiveActivities(Pageable pageable);
    
    /**
     * 根据商家查找活跃的团购活动
     */
    @Query("SELECT g FROM GroupBuyingActivity g WHERE g.merchantId = :merchantId AND g.status = 'active' AND g.endTime > CURRENT_TIMESTAMP ORDER BY g.createdAt DESC")
    Page<GroupBuyingActivity> findActiveActivitiesByMerchant(@Param("merchantId") Long merchantId, Pageable pageable);
    
    /**
     * 根据用户查找团购活动（我的团购）
     */
    @Query("SELECT g FROM GroupBuyingActivity g WHERE g.initiatorUserId = :userId ORDER BY g.createdAt DESC")
    Page<GroupBuyingActivity> findByInitiatorUserId(@Param("userId") Long userId, Pageable pageable);
    
    /**
     * 根据商品查找活跃的团购活动
     */
    @Query("SELECT g FROM GroupBuyingActivity g WHERE g.foodId = :foodId AND g.status = 'active' AND g.endTime > CURRENT_TIMESTAMP ORDER BY g.createdAt DESC")
    List<GroupBuyingActivity> findActiveActivitiesByFood(@Param("foodId") Long foodId);
    
    /**
     * 根据ID和发起人查找团购活动
     */
    Optional<GroupBuyingActivity> findByIdAndInitiatorUserId(Long id, Long initiatorUserId);
    
    /**
     * 根据状态查找团购活动 - AI推荐使用
     */
    @Query("SELECT g FROM GroupBuyingActivity g WHERE g.status = :status ORDER BY g.createdAt DESC")
    List<GroupBuyingActivity> findTop5ByStatusOrderByCreatedAtDesc(@Param("status") String status, Pageable pageable);
}

